package ch.reevolt.android.graphics;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;

/**
 * 
 * @author Romain Cherix
 * 
 *         This class is a graphic panel. It can be used to draw bitmap on the
 *         screen.
 * 
 */
public class PanelGraphics extends SurfaceView implements Callback {

	private CanvasThread canvasthread;
	private List<Drawable> pictures = Collections
			.synchronizedList(new ArrayList<Drawable>());

	/**
	 * 
	 * @param context
	 *            the Android context
	 */
	public PanelGraphics(Context context) {
		super(context);
		initialize();
	}

	/**
	 * 
	 * @param context
	 *            the Android context
	 * @param attrs
	 *            the Android attributes
	 */
	public PanelGraphics(Context context, AttributeSet attrs) {
		super(context, attrs);
		initialize();
	}

	/**
	 * 
	 * @param context
	 *            the Android context
	 * @param attrs
	 *            the Android attributes
	 * @param defStyle
	 *            Android defStyle
	 */
	public PanelGraphics(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initialize();
	}

	/**
	 * Initialize panel thread
	 */
	public void initialize() {
		getHolder().addCallback(this);
		canvasthread = new CanvasThread(getHolder(), this);
		setFocusable(true);
	}

	/**
	 * 
	 * @param picture
	 *            the picture to add to the PanelGraphics
	 */
	public void addDrawable(Drawable picture) {
		pictures.add(picture);
	}

	/**
	 * 
	 * @param picture
	 *            the picture to remove to the PanelGraphics
	 */
	public void removeDrawable(Drawable picture) {
		if (!pictures.remove(picture))
			new RuntimeException("Unable to remove element from graphical list");
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {

		canvasthread.setRunning(true);
		canvasthread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		canvasthread.setRunning(false);
		while (retry) {
			try {
				canvasthread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}

	@Override
	public void onDraw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);

		synchronized (pictures) {
			Iterator<Drawable> iterator = pictures.iterator();
			while (iterator.hasNext())
				iterator.next().draw(canvas);
		}
	}
}
